<template>
	<view class="container">
		<image v-if="contractUrl" :src="contractUrl" mode="widthFix" class="image"></image>
		<button v-show="isDisplay" class="floating-button" @tap="onSign">确认签署</button>
		<button v-show="isShowConfirm" class="floating-button" @tap="onConfirm">确认</button>
	</view>
</template>

<script>
	import {
		getContractByIdAPI,
		uploadSignatureByIdAPI
	} from '../../../api/common';

	export default {
		data() {
			return {
				contractUrl: '', // 用于存储Base64图片的Data URL
				orderId: '',
				isDisplay: false,
				isShowConfirm: false

			};
		},
		onLoad(option) {
			this.contractUrl = uni.getStorageSync('contractUrl')
			let flag = 0
			// console.log('state:', option.state);
			if (option.state === '1') {
				this.isDisplay = true
			}
			if (this.orderId != option.orderId) {
				this.orderId = option.orderId
				flag = 1
			}
			// console.log(this.orderId);
			if (!this.contractUrl || flag === 1) {
				this.getContract()
				flag = 0
			}
		},
		methods: {
			onSign() {
				uni.navigateTo({
					url: '/pages/salesman/signature/signature',
					success: () => {
						//隐藏按钮
						this.isDisplay = false
						this.isShowConfirm = true

						// 监听一次
						uni.$once('getSignImg', (e) => {
							// 多签名场景下可根据 sid 区分不同签名
							if (e.sid == 'sign-board') {
								this.signBase64 = e.base64
								this.signTempimg = e.path
								this.uploadSignatureById(e.base64)
							}
						})
					}
				})
			},
			onConfirm() {
				uni.switchTab({
					url: '/common/pages/order/order'
				})
				setTimeout(() => {
					this.isShowConfirm = false
				}, 1000)

			},
			async getContract() {
				try {
					uni.showLoading({
						title: '加载中...',
						mask: true
					})
					const res = await getContractByIdAPI(this.orderId)
					uni.hideLoading()
					this.contractUrl = `data:image/png;base64,${res}`
					uni.setStorageSync('contractUrl', this.contractUrl)
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: '获取失败',
						icon: 'none'
					})
				}
			},
			async uploadSignatureById(base64) {
				await uploadSignatureByIdAPI('a', this.orderId, base64)
				this.getContract()
				// uni.switchTab({
				// 	url:'/common/pages/order/order?orderId='+this.orderId
				// })
			}
		}
	}
</script>

<style>
	.container {
		padding: 20px;
	}

	.image {
		width: 100%;
		height: auto;
	}

	.floating-button {
		position: fixed;
		width: 450rpx;
		height: 100rpx;
		line-height: 62rpx;
		bottom: 6%;
		left: 50%;
		transform: translateX(-50%);
		padding: 10px 20px;
		background-color: #007aff;
		color: #ffffff;
		border: none;
		border-radius: 10px;
		z-index: 10;
	}
</style>